#include <sys/types.h>
#include <sys/fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include "server.h"


int give_me_a_socket_ready(){
    int s,b,l,on = 1, ret;
    struct sockaddr_in channel;

    memset(&channel, 0, sizeof(channel)); //inicializa la estructura a 0.
    channel.sin_family = AF_INET;
    channel.sin_addr.s_addr = htonl(INADDR_ANY);
    channel.sin_port = htons(SERVER_PORT);
    
    s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //create socket
    if (s<0) 
    {
        fprintf(stderr,"Socket failed.");
        return -1;
    }
    setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *) &on,sizeof(on));    

    b = bind(s, (struct sockaddr *) &channel, sizeof(channel));
    if (b<0) 
    {
        fprintf(stderr,"Bind failed.");
        return -1;
    }


    l = listen(s,QUEUE_SIZE);
    if (l<0) 
    {
        fprintf(stderr,"Listen failed.");
        return -1;
    }

    return s;
}

int wait_for_new_connection(int fd)
{
    int sa = accept(fd,0,0);
    if (sa<0) 
    {
        fprintf(stderr,"Accept failed.");
        return -1;
    }
    return (sa);
}

